package com.pakazaka.roguelike.ui;

import static com.pakazaka.simplecrawler.Core.getInstance;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Stack;

/**
 * @author Remi
 */
public class InGameConsole {

    private final Stack<ConsoleString> stack = new Stack<>();
    private boolean isFresh = true;
    private static final Color LAST_ACTIVE_MESSAGE = new Color(150, 0, 0);
    private static final Color DEBUG_MESSAGE = new Color(80, 80, 80);
    private static final Color NORMAL_MESSAGE = new Color(150, 150, 150);

    public boolean isIsFresh() {
        return isFresh;
    }

    public void setIsFresh(boolean isFresh) {
        this.isFresh = isFresh;
    }

    public void paint(Graphics g) {
        for (int i = 0; i < stack.size(); i++) {
            if (i == stack.size() - 1 && isFresh) {
                g.setColor(LAST_ACTIVE_MESSAGE);
            } else if (stack.get(i).getMessage().contains("DEBUG")) {
                g.setColor(DEBUG_MESSAGE);
            } else {
                g.setColor(NORMAL_MESSAGE);
            }
            g.drawString(stack.get(i).toString(), 312, 285 + 16 * i);
        }
        getInstance().repaint();
    }

    public void pushMessage(String msg) {
        isFresh = true;
        if (!stack.empty() && msg.equals(pullActualMessage())) {
            increaseTimesOfLastMessage();
        } else {
            stack.push(new ConsoleString(msg));
            if (stack.size() > 7) {
                stack.remove(0);
            }
        }
    }

    public void pushDebugMessage(String msg) {
        if (!stack.empty() && msg.equals(pullActualMessage())) {
            increaseTimesOfLastMessage();
        } else {
            stack.push(new ConsoleString("DEBUG: " + msg));
            if (stack.size() > 7) {
                stack.remove(0);
            }
        }
    }

    private String pullActualMessage() {
        return stack.peek().getMessage();
    }

    private void increaseTimesOfLastMessage() {
        stack.peek().increaseTimes();
    }

    private class ConsoleString {

        private final String message;
        private int timesMessaged = 1;

        ConsoleString(String message) {
            this.message = message;
        }

        public String getMessage() {
            return message;
        }

        @Override
        public String toString() {
            if (timesMessaged == 1) {
                return message;
            } else {
                return message + " x" + timesMessaged;
            }
        }

        public void increaseTimes() {
            timesMessaged++;
        }
    }
}
